package UDP.EchoServer;

import java.io.IOException;
import java.net.*;
import java.util.Scanner;

/**
 * 客户端  UdpEchoClient
 */
public class UdpEchoClient {

    private DatagramSocket socket = null;
    private String serverIP;
    private int serverPort;

    public UdpEchoClient(String ip,int port) throws SocketException {
        serverPort = port;
        serverIP = ip;
        socket = new DatagramSocket();
    }
    public void start() throws IOException {
        Scanner scanner = new Scanner(System.in);
        while (true){
            // 输入请求
            String request = scanner.next();
            DatagramPacket requestPacket = new DatagramPacket(request.getBytes(),request.getBytes().length,
                    InetAddress.getByName(serverIP),serverPort);
            socket.send(requestPacket);

            // 接收数据
            DatagramPacket respondPacket = new DatagramPacket(new byte[1024],1024);
            socket.receive(respondPacket);
            String response = new String(respondPacket.getData(),0,respondPacket.getLength(),"UTF-8");
            System.out.println(response);
        }
    }

    public static void main(String[] args) throws IOException {

        UdpEchoClient client = new UdpEchoClient("127.0.0.1", 9090);
        client.start();
    }
}
